import datetime
import json

from flask import Blueprint, jsonify, request

from utils.db import db1
from utils.redisconn import r
from utils.comm import get_data,gettree

bp_workflow = Blueprint('workflow',__name__)


@bp_workflow.route('/worklist')
def worklist():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({'code':200,'list':res})


@bp_workflow.route("/getsource")
def getsource():
    values = r.get_str("datasource")
    if values:
        lst = eval(values)
    else:
        sql = "select * from data_source"
        res = db1.find_all(sql)
        lst = []
        if res:
            for i in res:
                dic = {"id":i["id"],"name":i["name"]}
                msql = "select id,name,type from %s"%i["tablename"]
                mres = db1.find_all(msql)
                dic["mes"] = mres
                lst.append(dic)
        r.set_str("datasource",json.dumps(lst))

    return jsonify({"code":200,"list":lst})

@bp_workflow.route('/addworkflow',methods=["POST"])
def addworkflow():
    data = get_data()
    sql = "select * from workflow where id=%d"%int(data["id"])
    res = db1.find(sql)
    if res:
        usql = "update workflow set params='%s' where id=%d"%(str(data["list"]),int(res["id"]))
        db1.update(usql)
    return jsonify({"code":200,"msg":"修改成功"})

# 查询工作流
@bp_workflow.route("/query_workflow")
def query_workflow():
    sql = "select * from workflow"
    res = db1.find_all(sql)
    return jsonify({"code":200,"list":res})



@bp_workflow.route('/addtack', methods=['POST'])
def addtask():
    data = get_data()
    title = str(json.loads(data["params"])["姓名"]+data["title"])

    sql = "insert into task(title,params,status,userid,approver,next_approver) values('%s','%s',0,%d,'%s',%d)"%(title,data["params"],int(data["userid"]),data["approver"],int(json.loads(data["approver"])[0]))
    db1.update(sql)
    # key = "approver" + str(json.loads(data["approver"])[0])
    r.hset_key('approver',title,data["params"])
    return jsonify({"code":200,"msg":"添加成功"})

# 展示带用户的无限极分类
@bp_workflow.route('/getdept')
def getdept():
    sql = "select * from dept"

    res = db1.find_all(sql)

    list1 = gettree(res)

    return jsonify({'code':200,'list':list1})


# 查询请假工作流列表
#待我审批
@bp_workflow.route('/mytaskaudit')
def mytaskaudit():
    # id = request.args.get('id')
    # #从redis中获取我的任务列表
    # key='approver%d'%(int(id))
    # print(key)
    # task = r.hget_keys(key)
    task = r.hget_keys('approver')
    list=[]
    for k,v in task.items():
        id = str(k,encoding='utf8')
        title = str(v,encoding='utf8')
        list.append({'name':id,'title':title})
        # print(list)

    return jsonify({"code":200,'list':list})





@bp_workflow.route('/mytask')
def mytask():
    id = request.args.get("userid")
    sql = "select * from user where id=%d"%int(id)
    res = db1.find(sql)
    # print(res)
    if res:
    #     lst = []
    #     key = "approver"+str(res["id"])
    #     list = r.hget_keys(key)
    #     for k,v in list.items():
    #         lst.append({"name":str(k,encoding="utf8"),"title":str(v,encoding="utf8")})
    #     return jsonify({"code":200,"list":lst})
    # return jsonify({"code":403,"msg":"id篡改"})
          sql = "select * from task where userid=%d"%int(id)
          res = db1.find_all(sql)
          return jsonify({"code":200,"list":res})




@bp_workflow.route('/taskm', methods=['POST', 'GET'])
def taskm():
    if request.method == "POST":
        data = get_data()

        title = data['title']
        params = data['params']
        approver = data['approver']
        # 添加任务
        sql = "insert into task(title,params,next_audit,status,approver) values('%s','%s','%s',1,%d)" % (
        title, params, approver, approver[0])
        db1.update(sql)

        sql1 = "select id,title from task where title='%s'" % (title)
        task = db1.find(sql1)
        # 把当前任务加到redis中，选用hash类型
        key = 'task%d' % (approver[0])
        r.hset_key(key, task['id'], task['title'])
        return jsonify({"code": 200})
    else:
        # 通过任务id获取任务信息及对应的审批信息

        userid = request.args.get('userid')
        if userid:
            sql = "select * from task where userid=%d" % (int(userid))
            res = db1.find_all(sql)
            return jsonify({"code": 200, 'list': res})

        id = request.args.get('id')
        sql = "select * from task where id=%d" % (int(id))

        task = db1.find(sql)
        # 此任务相关的审批记录
        sql1 = "select * from audit_record where taskid=%d" % (int(id))
        records = db1.find_all(sql1)
        task['audit_records'] = records
        return jsonify({"code": 200, 'task': task})


@bp_workflow.route('/taskquery')
def taskquery():
    taskid = request.args.get("taskid")
    sql = "select * from task where id='%s'"%int(taskid)
    res = db1.find(sql)
    return jsonify({"code":200,"list":res})



@bp_workflow.route('/taskrecordM', methods=['POST'])
def taskrecordM():
    data = get_data()
    # 写审批记录表
    time = datetime.datetime.strftime(datetime.datetime.now(), '%Y-%m-%d %H:%M:%S')
    try:
        sql = "insert into audit_record(taskid,userid,username,is_agree,reason,add_time) values(%d,%d,'%s',%d,'%s','%s')" % (
        int(data['taskid']), int(data['userid']), data['name'], int(data['agree']), data['reason'], time)
        db1.add(sql)
    except:
        return jsonify({"code": 10010, 'mes': '审批失败'})

    # 判断是否同意
    tsql = "select * from task where id=%d" % (int(data['taskid']))
    task = db1.find(tsql)
    key = 'task%d' % (int(data['userid']))
    # 清除当前redis中的信息
    r.del_hash(key, int(data['taskid']))
    auditlist = json.loads(task['next_audit'])
    # 是不是最后一个审批人
    index = auditlist.index(data['userid'])
    if data['agree'] == '1':
        try:
            # 同意，查询任务，更新下一审批人，redis清除当前审批人，加入下一审批人，
            # 任务表中更新任务状态，如果是最后一个审批人，查新成已经完成，其它审核中
            if index == len(auditlist) - 1:
                sql1 = "update task set status=3,nexta=0 where id=%d" % (int(data['taskid']))
                db1.add(sql1)
            else:
                sql1 = "update task set status=2,nexta=%d where id=%d" % (auditlist[index + 1], int(data['taskid']))
                db1.add(sql1)
                # 添加redis
                newkey = 'task%d' % (int(auditlist[index + 1]))
                # 把下一审批人加入到redis
                r.hset_key(newkey, int(data['taskid']), task['title'])
            db1.commit()
        except:
            db1.rollback()
            return jsonify({"code": 10020, 'mes': '失败'})
    else:
        # 不同意，把redis中当前审批人清除，任务表中的下一审批人清空
        if index == 0:
            sql1 = "update task set status=1,nexta=0 where id=%d" % (int(data['taskid']))
            db1.update(sql1)
        else:
            sql1 = "update task set nexta=%d where id=%d" % (int(auditlist[index - 1]), int(data['taskid']))
            db1.update(sql1)
            # 添加redis
            newkey = 'task%d' % (int(auditlist[index - 1]))
            # 把下一审批人加入到redis
            r.hset_key(newkey, int(data['taskid']), task['title'])
    return jsonify({"code": 200})

